package db

import (
	"context"
	"encoding/json"
	{{.Path}} "ics/apps/{{.Path}}/document"
	"fmt"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"gitee.com/dreamwood/ez-go/tools"
	"go.mongodb.org/mongo-driver/bson"
	"os"
	"testing"
)

func Drop{{.Name}}() {
	ez.DBMongo.Collection("{{.Name}}").Drop(context.TODO())
}
func TestDrop{{.Name}}(t *testing.T) {
	ez.DefaultInit()
	Drop{{.Name}}()
}
func BackUp{{.Name}}(targetFile string) {
	if targetFile == "" {
		targetFile = "./{{.Name}}.json"
	}
	ez.DefaultInit()
	//计数
	total, e := ez.DBMongo.Collection("{{.Name}}").CountDocuments(context.TODO(), bson.M{})
	if e != nil {
		ez.LogToConsole(e.Error())
	}
	f, e := os.OpenFile(targetFile, os.O_CREATE|os.O_WRONLY|os.O_RDWR, 0666)
	if e != nil {
		ez.LogToConsole(e.Error())
	}
	defer f.Close()
	crud := {{.Path}}.New{{.Name}}Crud()
	data := make([]{{.Path}}.{{.Name}}, 0)
	for i := 0; i <= int(total/1000); i++ {
		rows, e := crud.FindBy(ss.M{}, nil, i, 1000)
		if e != nil {
			ez.LogToConsole(e.Error())
		}
		for _, row := range rows {
			data = append(data, *row)
		}
	}
	content, e := json.Marshal(data)
	f.Write(content)
}
func TestBackUp{{.Name}}(t *testing.T) {
	ez.DefaultInit()
	targetFile := fmt.Sprintf("./{{.Name}}_%s.json", tools.GetDateYMDHIS("", "", "_"))
	BackUp{{.Name}}(targetFile)
}
func Recover{{.Name}}(filePath string) {
	if filePath == "" {
		filePath = "./{{.Name}}.json"
	}
	ez.DefaultInit()
	ez.DBMongo.Collection("{{.Name}}").Drop(context.TODO())
	content := tools.ReadFile(filePath)
	data := make([]{{.Path}}.{{.Name}}, 0)
	e := json.Unmarshal(content, &data)
	if e != nil {
		ez.LogToConsole(e.Error())
	}
	for _, row := range data {
		e = row.Create()
		if e != nil {
			ez.LogToConsole(e.Error())
		}
	}
	ez.LogToConsole(fmt.Sprintf("写入数据%d条", len(data)))
}
func TestRecover{{.Name}}(t *testing.T) {
	filePath := "./{{.Name}}_20240107_190550.json"
	ez.DefaultInit()
	Recover{{.Name}}(filePath)
}
